package it.gtd.swimpool.controller.resources;

import it.gtd.swimpool.model.business.CommunicationManager;
import it.gtd.swimpool.model.entity.Message;
import it.gtd.swimpool.model.entity.User;

import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.text.DateFormat;
import java.text.ParseException;
import java.util.Date;
import java.util.List;

@Stateless
@Path("/")
public class MessageResource extends SecuredResource {
    @PersistenceContext
    private EntityManager entityManager;

    @EJB
    private CommunicationManager communicationManager;

    @GET
    @Path("/self/messages")
    public List<Message> getOwnMessages(
        @CookieParam(Cookie.SESSION_ID) String sessionId,
        @QueryParam("sender") int senderId,
        @QueryParam("since") @DefaultValue("") String since,
        @QueryParam("to") @DefaultValue("") String until
    ) {
        User caller = checkUser(sessionId);
        User sender = entityManager.find(User.class, senderId);
        Date sinceDate = null, untilDate = null;

        try {
            if (!since.isEmpty()) {
                sinceDate = DateFormat.getDateInstance(DateFormat.SHORT).parse(since);
            }

            if (!until.isEmpty()) {
                untilDate = DateFormat.getDateInstance(DateFormat.SHORT).parse(until);
            }

        } catch (ParseException pex) {
            throw new WebApplicationException(pex, Response.Status.INTERNAL_SERVER_ERROR);
        }

        return communicationManager.getMessages(caller, sender, sinceDate, untilDate);
    }

    @POST
    @Path("/users/{id}/messages")
    @Consumes(MediaType.TEXT_PLAIN)
    public void sendMessage(
        @CookieParam(Cookie.SESSION_ID) String sessionId,
        @PathParam("id") int recipientId,
        String text
    ) {
        User caller = checkUser(sessionId);
        User recipient = entityManager.find(User.class, recipientId);

        text = escape(text);

        communicationManager.sendMessage(caller, recipient, text);
    }
}
